<?php

namespace App\Model\Rbac;

use App\Model\CrudModel;

/**
 * @property int $id
 * @property int $deleted_at 删除标识
 * @property int $pid 上级id
 * @property int $type RouteCode::TYPE_xxx
 * @property string $path 资源路径，唯一
 * @property  array $header 表单校验的规则
 * @property array $custom_rule 自定义的结合业务需要的规则 <pre>
 *  [
 *      'mustLogin', // 必须携带有效的token并解析出正确的用户信息
 *      'realNameAuth', // 实名认证
 *      'adminPowerCheck', // 账号必须有此接口的权限
 *  ]
 * </pre>
 * @property array $rate_limit <pre
 * [
 *  'rate' => 100,60
 *  'by' => path | ?ip | path_ip | path_uid |
 * ]
 * @property int $created_at
 * @property int $updated_at
 * </pre>
 */
class RouteModel extends CrudModel
{

    // 所有的api
    protected ?string $table = 'route';

    protected array $searchAllowEmpty = [
        'path',
    ];

    protected array $casts = [
        'header' => 'array',
        'custom_rule' => 'array',
        'rate_limit' => 'array',
    ];

    public function addOne(array $data)
    {
        $now = time();
        return $this->insert([
            'pid' => intval($data['pid']),
            'type' => intval($data['type']),
            'name' => trim($data['name']),
            'path' => trim($data['path']),
            'header' => json_encode($data['header'] ?? []),
            'custom_rule' => json_encode($data['custom_rule'] ?? []),
            'rate_limit' => json_encode($data['rate_limit'] ?? []),
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    /**
     * @param $path
     * @param $type
     * @param $field
     * @return \Hyperf\Database\Model\Model|object|null|static
     */
    public function findByPath($path, $type=null, $field=['*'])
    {
        $where = ['path'=>$path];
        if ($type){
            $where['type'] = $type;
        }
        return $this->buildQuery($where)->first($field);
    }

    public function updateById($id, array $data)
    {
        return $this->buildQuery(['id'=>$id,])->update([
            'pid' => intval($data['pid']),
            'type' => intval($data['type']),
            'name' => trim($data['name']),
            'path' => trim($data['path']),
            'header' => json_encode($data['header'] ?? []),
            'custom_rule' => json_encode($data['custom_rule'] ?? []),
            'rate_limit' => json_encode($data['rate_limit'] ?? []),
            'updated_at' => time(),
        ]);
    }
}